package com.avecsys.quotemanager.mbeans.buyer;

import java.io.Serializable;
import java.util.Map;

import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.exception.UserSessionNotFoundException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.BuyerMasterPojo;
import com.avecsys.quotemanager.pojos.BuyerUsersPojo;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.pojos.SupplierUsersPojo;
import com.avecsys.quotemanager.service.buyer.BuyerMasterService;
import com.avecsys.quotemanager.service.common.CommonService;
import com.avecsys.quotemanager.service.supplier.SupplierMasterService;
import com.avecsys.quotemanager.service.user.UserMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.TransactionStatus;

public class BuyerUsersMBean extends BaseMBean implements Serializable {

	private final Log log = LogFactory.getLog(BuyerUsersMBean.class);

	private BuyerMasterService buyerMasterService;

	private UserMasterService userMasterService;

	private CommonService commonService;

	private BuyerUsersPojo buyerUsersPojo = new BuyerUsersPojo();

	private String selectedBuyerId;

	private String selectedBuyerCompanyName;

	private String confirmPassword;

	private String existingEmailAddress;

	
	public BuyerMasterService getBuyerMasterService()
	{
		return buyerMasterService;
	}

	public void setBuyerMasterService(BuyerMasterService buyerMasterService)
	{
		this.buyerMasterService = buyerMasterService;
	}

	public BuyerUsersPojo getBuyerUsersPojo()
	{
		return buyerUsersPojo;
	}

	public void setBuyerUsersPojo(BuyerUsersPojo buyerUsersPojo)
	{
		this.buyerUsersPojo = buyerUsersPojo;
	}

	public String getSelectedBuyerId()
	{
		return selectedBuyerId;
	}

	public void setSelectedBuyerId(String selectedBuyerId)
	{
		this.selectedBuyerId = selectedBuyerId;
	}

	public String getSelectedBuyerCompanyName()
	{
		return selectedBuyerCompanyName;
	}

	public void setSelectedBuyerCompanyName(String selectedBuyerCompanyName)
	{
		this.selectedBuyerCompanyName = selectedBuyerCompanyName;
	}


	public String actionCancel() {
		try {
			FacesContext faceContext = FacesContext.getCurrentInstance();
			Map<String, String> paramValues = faceContext.getExternalContext()
					.getRequestParameterMap();
			String selectedBuyerId = paramValues.get("selectedBuyerId");
			BuyerMasterPojo selectedBuyerMasterPojo = buyerMasterService
					.getBuyerMasterById(new Long(selectedBuyerId));
			BuyerUsersListMBean buyerUsersListMbean = (BuyerUsersListMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{buyerUsersListMBean}",
							BuyerUsersListMBean.class);
			buyerUsersListMbean
					.loadAllUsersByBuyer(selectedBuyerMasterPojo);
		} catch (BusinessException e) {
			log.error(e);
		}
		return "openListUsersForBuyer";
	}

	/**
	 * Action Method to save buyer user Information
	 * 
	 * @return Navigation Page
	 */
	public String actionSaveBuyerUser() {
		try {
			log.info("Started Saving Buyer User Information into database");
			// Step1: Update user modification information
			updateUserInformation(buyerUsersPojo);
			// Step2: Get the Buyer Pojo associate to the user
			BuyerMasterPojo selectedBuyerMasterPojo = buyerMasterService
					.getBuyerMasterById(new Long(getSelectedBuyerId()));
			buyerUsersPojo.setBuyerMasterPojo(selectedBuyerMasterPojo);
			// Mark Email Verified status as false if the email is different
			// from the current one
			if (getExistingEmailAddress() != null
					&& !getExistingEmailAddress().equalsIgnoreCase(
							buyerUsersPojo.getUserMasterPojo().getEmail())) {
				buyerUsersPojo.getUserMasterPojo().setEmailVerfied(
						Boolean.FALSE.toString());
			}
			TransactionStatus transactionStatus = userMasterService
					.saveBuyerUser(buyerUsersPojo);
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.BUYER_USER, "messageBoardId", "",
					new Object[] { buyerUsersPojo.getUserMasterPojo()
							.getUserName() });
			// Refresh the Buyer users list
			FacesContext faceContext = FacesContext.getCurrentInstance();
			BuyerUsersListMBean buyerUsersListMBean = (BuyerUsersListMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{buyerUsersListMBean}",
							BuyerUsersListMBean.class);
			buyerUsersListMBean
					.loadAllUsersByBuyer(selectedBuyerMasterPojo);
			// Send Verification Email
			if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.SAVE_SUCESS
					.ordinal()) {
				log.info("Sending Activate Email Notification to Buyer User");
				commonService.sendEmail(buyerUsersPojo);
			} else if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.UPDATE_SUCCESS
					.ordinal()) {
				// Send Notification only if user changed existing email address
				if (!getExistingEmailAddress().equalsIgnoreCase(
						buyerUsersPojo.getUserMasterPojo().getEmail())) {
					log.info("Sending Activate Email Notification to Buyer User");
					commonService.sendEmail(buyerUsersPojo);
				}
			}
			log.info("Completed saving Buyer User Information into database sucessfully");
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		return "openListUsersForBuyer";
	}

	public CommonService getCommonService() {
		return commonService;
	}

	/**
	 * @return the confirmPassword
	 */
	public String getConfirmPassword() {
		return confirmPassword;
	}

	public String getExistingEmailAddress() {
		return existingEmailAddress;
	}

	

	/**
	 * @return the userMasterService
	 */
	public UserMasterService getUserMasterService() {
		return userMasterService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * @param confirmPassword
	 *            the confirmPassword to set
	 */
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public void setExistingEmailAddress(String existingEmailAddress) {
		this.existingEmailAddress = existingEmailAddress;
	}

	/**
	 * @param userMasterService
	 *            the userMasterService to set
	 */
	public void setUserMasterService(UserMasterService userMasterService) {
		this.userMasterService = userMasterService;
	}

	/**
	 * Method to update the user information
	 * 
	 * @param buyerUsersPojo
	 * @throws UserSessionNotFoundException
	 */
	public void updateUserInformation(BuyerUsersPojo buyerUsersPojo)
			throws UserSessionNotFoundException {
		// Update User Information to Supplier
		super.updateUserInformation(buyerUsersPojo, null);
		// Update User Information to Company
		super.updateUserInformation(buyerUsersPojo.getUserMasterPojo(),
				buyerUsersPojo.getModifiedDttm());
	}
}
